package com.gzu.se.interceptor;

import com.gzu.se.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired JwtUtil jwtUtils;
//    private static final Logger log = LoggerFactory.getLogger(LoginCheckInterceptor.class);

    @Override//目标资源方法运行前运行，返回true:放行，放回false，不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url=request.getRequestURI().toString();
        log.info("请求的url：{}",url);
        //2判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(url.contains("login")||url.contains("register")){
            log.info("登陆或注册操作，放行");
            return true;
        }
        //3获取请求头中的令牌(token)
        String token=request.getHeader("token");
        //4判断令牌是否存在，如果不存在，返回错误结果(未登录)
        if(!StringUtils.hasLength(token)){
            log.info("请求头token为空，返回未登陆信息");
            response.getWriter().write("NOT_LOGIN");
            return false;
        }
        //5验证token
        if(!jwtUtils.validateToken(token)){
            log.info("验证令牌失败，返回未登录信息");
            response.getWriter().write("NOT_LOGIN");
            return false;
        }
        //6放行
        log.info("令牌合法,放行");
        return true;
    }

    @Override//标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle运行了");
    }

    @Override//视图渲染完毕后运行，最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion运行了");
    }
}